//
//  JMTabBar.m
//  OC-Sina
//
//  Created by 陈高健 on 15/12/21.
//  Copyright © 2015年 陈高健. All rights reserved.
//

#import "JMTabBar.h"

@interface JMTabBar ()

//放大按钮
@property (nonatomic,weak)UIButton *plusButton;
@end

@implementation JMTabBar

//编译器认为自定义的成员与父类重名,所以我们可以使用dynamic来解决
@dynamic delegate;

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
       //创建加号按钮
        UIButton * button = [[UIButton alloc]init];
        //设置背景图片
        [button setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"tabbar_compose_button_highlighted"] forState:UIControlStateHighlighted];
        //设置图片
        [button setImage:[UIImage imageNamed:@"tabbar_compose_icon_add"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] forState:UIControlStateHighlighted];
        //设置按钮大小等于当前背景图片的大小
        button.size = button.currentBackgroundImage.size;
        
        //添加放大按钮的点击事件
        [button addTarget:self action:@selector(didSelectPlusButton:) forControlEvents:UIControlEventTouchUpInside];
        
        //添加到视图上
        [self addSubview:button];
        //赋值
        self.plusButton = button;
        
    }
    return self;
}

//调整按钮的位置
- (void)layoutSubviews{
    [super layoutSubviews];
    
    //设置plusButton的位置为中心位置
    self.plusButton.centerX = (self.width * 0.5);
    self.plusButton.centerY = (self.height * 0.5);

    //取出所有子控件的个数
    NSInteger count = self.subviews.count;
    //判断按钮的索引
    NSInteger index = 0;
    
    CGFloat buttonW = self.bounds.size.width / 5;
    for (int i = 0 ; i < count; i++) {
        UIView *childView = self.subviews[i];
        if ([childView isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            //计算每个控件的坐标
            childView.width = buttonW;
            childView.x = buttonW * index;
            
            index ++;
            //判断是否是中间的按钮,如果是直接跳过,也就是直接计算下一下按钮的坐标
            if (index == 2) {
                index ++;
            }
        }
    }
}

//点击放大按钮的点击事件
- (void)didSelectPlusButton:(UIButton *)button {
    //判断代理是否存在
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectPlusButton:)]) {
        //执行代理
        [self.delegate tabBar:self didSelectPlusButton:button];
    }
}
@end
